<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Jobs\PushNotificationJob;
use App\Models\User;
use App\Service\Firebase;
use App\Service\Push;

class BatchNotifyController extends Controller
{


    /**
     * 队列发送通知
     */
    public function sendFcm()
    {
        $deviceTokens = User::where('status',1)
            ->pluck('device_token')
            ->toArray();
        PushNotificationJob::dispatch('sendBatchNotification', [
            $deviceTokens,
            [
                'topicName' => 'global',
                'title' => 'this is a test-title--2222',
                'data'  => 'body-Payload',
                'body'  => 'body-Payload',
                'image' => 'https://picsum.photos/536/354',
            ],
        ])->onQueue('fcmTasks');
    }


    /**
     * 线程处理
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendMultiFcm()
    {
        $data = json_decode( \request()->getContent() );

        $payload = $data->payload ?? [
                'aps' => [
                    'mutable-content' => 1,
                    'category' => 'NEW_MESSAGE_CATEGORY'
                ],];
        $title = $data->title ?? 'this is a test-title';
        $message = $data->message ?? 'test--milo';            // notification message
        $push_type = $data->push_type ?? 'individual';            // push type - single user / topic
        $body = $data->body ?? '这是一个测试body!!!!';

        $push = new Push();
        $firebase = new Firebase();
        try {
            $push->setTitle( $title )
                ->setMessage( $message )
                ->setPayload( $payload )
                ->setData($body);
            $response = '';
            $json     = $push->getPush();

            if ( $push_type === 'topic' ) {
                $response = $firebase->sendToTopic( 'global', $json );
            } else if ( $push_type === 'individual' ) {
                // 数据库拿回token
                $deviceTokens = User::where('status',1)
                    ->pluck('device_token')
                    ->toArray();
                $regIds   = $deviceTokens ?? [];
                $response = $firebase->sendMultiple( $regIds, $json );
            }
            return response()->json( [
                'response' => $response
            ] );
        } catch ( \Exception $ex ) {
            return response()->json( [
                    'error'   => true,
                    'message' => $ex->getMessage()
            ]);
        }
    }

}